<template>
  <div class="StorePower flc pad_10_16" :style="{ paddingTop: `${45 + statusBarHeight}px` }">
    <NavBar 
      :navBarStyle="{
        backgroundColor: navBarBg,
        height: `${45 + statusBarHeight}px`,
        paddingTop: `${statusBarHeight}px`,
      }"
      pageName="授权店铺"
      @onLeftClick="leftBack" 
    >
      <div slot="nav-right" class="fl vc end">
        <!-- <div class="img36 flvcc" @click="$router.push({ name: 'couponGrant' })">
          <img src="@/assets/images/icon_grant.png" class="img24" />
        </div> -->
        <div class="img36 flvcc" @click="showSearch = !showSearch">
          <img src="@/assets/images/icon_search.png" class="img24" />
        </div>
      </div>
    </NavBar>
    <div class="fls fl vc mb10" v-if="showSearch">
      <van-field
        v-model.trim="queryParams.storeName"
        left-icon="search"
        placeholder="输入关键字"
      />
      <p class="dx_15 color_16 fl end wb20" @click="resetSearch">搜索</p>
    </div>
    <div class="hb flau">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div class="wb bg_fff bkra8 mb10" v-for="(item, index) in storeList" :key="item.storeId">
          <StoreItem :item="item"></StoreItem>
          <div class="plr_10 pdb_10 flvcbt" @click="openSetting(item.scriptList, scriptList, index, item.storeId, item.shopName)">
            <div class="fl vc">
              <div class="fl vc">
                <img src="@/assets/images/icon_unpower.png" class="img16 mr5 fls" />
                <p class="dx_14">未授权剧本({{ scriptList.length - item.scriptList.length > 0 ? scriptList.length - item.scriptList.length : 0 }})</p>
              </div>
              <div class="fl vc ml8">
                <img src="@/assets/images/icon_power.png" class="img16 mr5 fls" />
                <p class="dx_14">已授权剧本({{ item.scriptList.length }})</p>
              </div>
            </div>
            <img class="expand_icon rotate_icon" src="@/assets/images/icon_rotate.png" />
          </div>
          <!-- <div class="plr_10">
            <div class="flvcbt" @click="handleExpand(index)">
              <div class="apply_wrap fl vc">
                <img src="@/assets/images/icon_power.png" class="img16 mr5 fls" />
                <p class="dx_14 ct">未授权剧本（{{ item.unPowerList.length }}）</p>
              </div>
              <img class="expand_icon rotate_icon" :class="item.unPowerExpand ? 'rotate_top' : ''" src="@/assets/images/icon_rotate.png" />
            </div>
            <div class="pad_10" @click="openSetting(item.checkList, item.unPowerList, 1, index, item.storeId, item.shopName)">
              <van-checkbox-group v-model="item.checkList" v-if="item.unPowerExpand">
                <van-checkbox :name="el.id" v-for="el in item.unPowerList" :key="el.id" checked-color="#D1FB71" shape="square">{{ el.title }}</van-checkbox>
              </van-checkbox-group>
            </div>
            <div class="flvcbt" @click="handlePowerExpand(index)">
              <div class="apply_wrap fl vc">
                <img src="@/assets/images/icon_power.png" class="img16 mr5 fls" />
                <p class="dx_14 ct">已授权剧本（{{ item.powerList.length }}）</p>
              </div>
              <img class="expand_icon rotate_icon" :class="item.powerExpand ? 'rotate_top' : ''" src="@/assets/images/icon_rotate.png" />
            </div>
            <div class="pad_10" @click="openSetting(item.unCheckList, item.powerList, 2, index, item.storeId, item.shopName)">
              <van-checkbox-group v-model="item.unCheckList" v-if="item.powerExpand">
                <van-checkbox :name="el.id" v-for="el in item.powerList" :key="el.id" checked-color="#D1FB71" shape="square">{{ el.title }}</van-checkbox>
              </van-checkbox-group>
            </div>
          </div> -->
          
        </div>
      </van-list>
    </div>
    <PowerSetting ref="PowerSetting" @close="handleClose" @refresh="handleRefresh"></PowerSetting>
  </div>
</template>

<script>
import NavBar from '@/components/NavBar/NavBar.vue'
import PowerSetting from './components/PowerSetting.vue'
import StoreItem from './components/StoreItem.vue'
import { List, Checkbox, CheckboxGroup, Field } from 'vant';
// import { Toast } from 'vant';
import { navOtherHeight } from '@/config/config'
import { formatterStatus, fnOmit } from '@/utils/util'
import { getStoreList } from '@/api/store.js'
import { getScriptList } from '@/api/chart.js'

export default {
  components: {
    [List.name]: List,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Field.name]: Field,
    NavBar,
    StoreItem,
    PowerSetting
  },

  data() {
    return {
      formatterStatus,
      fnOmit,
      navBarBg: 'transparent',
      navigationHeight: 47,
      statusBarHeight: 0,
      navOtherHeight,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeName: ''
      },
      showSearch: false,
      loading: true,
      finished: false,
      storeList: [],
      scriptList: []
    };
  },

  watch: {
    "$store.state.token": {
      handler:function() { 
        this.getScriptList()
        this.getStoreList()
      }
    }
  },

  created() {
    this.getAPPNavHeight()
    if (this.$store.state.token) {
      this.getScriptList()
      this.getStoreList()
    }
  },

  methods: {
    onLoad() {
      console.log('到底')
      this.queryParams.pageNum += 1
      this.getStoreList()
    },
    resetSearch() {
      this.queryParams.pageNum = 1
      this.getStoreList()
    },

    // 打开授权剧本
    openSetting(checkList, allList, type, index, storeId, storeName) {
      console.log(checkList, allList, type, index)
      const checkedList = JSON.parse(JSON.stringify(checkList))
      this.$refs.PowerSetting.initData(checkedList, allList, type, index, storeId, storeName)
    },

    handleClose(index, type) {
      if (type == 1) {
        this.storeList[index].checkList = []
      } else {
        this.storeList[index].unCheckList = this.storeList[index].powerList.map(item => {
          return item.id
        })
      }
    },

    handleRefresh(index, list) {
      this.storeList[index].scriptList = list
    },
    // 未授权和已授权分开版
    // handleRefresh(index, list, type) {
    //   console.log(list)
    //   if (type == 1) {
    //     this.storeList[index].checkList = []
    //     this.storeList[index].unPowerList = this.storeList[index].unPowerList.filter(item => !list.includes(item.id))
    //     list.forEach(item => {
    //       const obj = this.scriptList.find(el => el.id == item)
    //       this.storeList[index].powerList.unshift(obj)
    //       this.storeList[index].unCheckList.unshift(item)
    //     })
    //   } else {
    //     this.storeList[index].powerList = this.storeList[index].powerList.filter(item => !list.includes(item.id))
    //     this.storeList[index].unCheckList = this.storeList[index].powerList.map(item => {
    //       return item.id
    //     })
    //     list.forEach(item => {
    //       const obj = this.scriptList.find(el => el.id == item)
    //       this.storeList[index].unPowerList.unshift(obj)
    //       // this.storeList[index].unCheckList.push(item)
    //     })
    //   }
    // },

    handleExpand (index) {
      this.storeList[index].unPowerExpand = !this.storeList[index].unPowerExpand
    },
    handlePowerExpand (index) {
      this.storeList[index].powerExpand = !this.storeList[index].powerExpand
    },

    leftBack () {
      console.log('点击了', window)
      if (window.androidJSBridge) {
        window.androidJSBridge.back()
      } else if (window.webkit) {
        console.log('ios')
        window.webkit.messageHandlers.back.postMessage({})
      }
    },

    getAPPNavHeight () {
      console.log('--appNavigation--', window)
      if (window.androidJSBridge) {
        const result = JSON.parse(window.androidJSBridge.appNavigation())
        this.navigationHeight = result.navigationHeight
        this.statusBarHeight = result.statusBarHeight
        document.documentElement.style.setProperty('--navHeight', this.navigationHeight + 'px')
        console.log('android1', result)
      } else if (window.webkit) {
        console.log('ios-appNavigation')
        window.appNavigation = this.onAppNavigation
        window.webkit.messageHandlers.appNavigation.postMessage({})
      } else {
        this.navigationHeight = 0
        document.documentElement.style.setProperty('--navHeight', this.navigationHeight + 'px')
      }
    },

    onAppNavigation (result) {
      console.log('ios--appNavigation', result)
      this.navigationHeight = Number(result.navigationHeight)
      this.statusBarHeight = Number(result.statusBarHeight)
      document.documentElement.style.setProperty('--navHeight', this.navigationHeight + 'px')
    },

    // 获取店铺列表
    async getStoreList () {
      try {
        const params = {
          request: {
            dto: {
              ...this.queryParams
            }
          }
        }
        const res = await getStoreList(params)
        console.log('店铺列表', res)
        if (res.errorCode === 0) {
          if (res.response.records.length) {
            res.response.records.forEach(el => {
              el.unPowerList = this.scriptList.filter(item => !el.scriptList.includes(item.id))
              el.powerList = this.scriptList.filter(item => el.scriptList.includes(item.id))
              el.unPowerExpand = false
              el.powerExpand = false
              el.checkList = []
              el.unCheckList = el.powerList.map(item => {
                return item.id
              })
            })
            console.log('list:', res.response.records)
            this.storeList = this.queryParams.pageNum > 1 ? [...this.storeList, ...res.response.records] : res.response.records
          }
          else {
            this.storeList = this.queryParams.pageNum > 1 ? this.storeList : res.response.records
          }
          if (res.response.records.length < this.queryParams.pageSize) {
            this.finished = true
            this.loading = true
          } else {
            this.finished = false
            this.loading = false
          }
        }
      } catch (error) {
        console.error(error)
      }
    },

    // 获取剧本列表
    async getScriptList () {
      try {
        const params = {
          request: {
            boxFlag: true
          }
        }
        const res = await getScriptList(params)
        console.log('剧本列表', res)
        if (res.errorCode === 0) {
          this.scriptList = res.response
        }
      } catch (error) {
        console.error(error)
      }
    }
  }
};
</script>

<style lang="less">
.StorePower {
  height: calc(100vh - var(--navHeight));
  .van-checkbox__label {
    font-size: 16px;
    font-weight: bold;
    margin-left: 15px;
  }
  .van-checkbox__icon .van-icon {
    border-radius: 5px;
  }
  .van-checkbox {
    padding: 12px 0;
  }
  .van-cell {
    border-radius: 8px;
  }
}
.pad_10_16 {
  padding: 10px 16px;
}
.pad_12 {
  padding: 12px;
}
.pdl_12 {
  padding-left: 12px;
}
.apply_wrap {
  border-radius: 6px;
  background: linear-gradient(90deg, rgba(209, 251, 113, 0.32) 0%, rgba(209, 251, 113, 0.00) 100%);
  font-size: 15px;
  padding: 4px 8px;
}

.expand_icon {
  width: 16px;
  height: 16px;
  display: block;
}
.is_expand {
  white-space: normal;
  overflow: visible;
}
.rotate_icon {
  transition: all 0.3s;
}
.rotate_top {
  transform: rotate(180deg);
}

</style>
